import { get, post, put, del } from "./api";

export const jobTypeService = {
  async getJobTypes(params = { page: 1, pageSize: 10 }) {
    try {
      const response = await get("job-types");
      const allJobTypes = Array.isArray(response)
        ? response
        : response.content || [];

      // 按ID升序排序
      const sortedJobTypes = allJobTypes.sort((a, b) => a.id - b.id);

      // 如果pageSize为1000，表示要获取所有数据用于搜索
      if (params.pageSize === 1000) {
        return {
          items: sortedJobTypes,
          total: sortedJobTypes.length,
          totalPages: 1,
          currentPage: 1,
        };
      }

      const startIndex = (params.page - 1) * params.pageSize;
      const endIndex = startIndex + params.pageSize;
      const paginatedJobTypes = sortedJobTypes.slice(startIndex, endIndex);

      return {
        items: paginatedJobTypes,
        total: allJobTypes.length,
        totalPages: Math.ceil(allJobTypes.length / params.pageSize),
        currentPage: params.page,
      };
    } catch (error) {
      throw new Error(error.message || "获取工作类型列表失败");
    }
  },

  async getAllJobTypes() {
    try {
      const response = await get("job-types");
      return Array.isArray(response) ? response : response.content || [];
    } catch (error) {
      throw new Error(error.message || "获取工作类型列表失败");
    }
  },

  async getJobType(id) {
    try {
      const jobTypeId = parseInt(id);
      if (isNaN(jobTypeId)) {
        throw new Error("无效的工作类型ID");
      }
      const response = await get(`job-types/${jobTypeId}`);
      return response;
    } catch (error) {
      if (error.response?.status === 404) {
        throw new Error("工作类型不存在");
      }
      throw new Error(error.message || "获取工作类型信息失败");
    }
  },

  async createJobType(jobTypeData) {
    try {
      const response = await post("job-types", jobTypeData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "创建工作类型失败");
    }
  },

  async updateJobType(id, jobTypeData) {
    try {
      const jobTypeId = parseInt(id);
      if (isNaN(jobTypeId)) {
        throw new Error("无效的工作类型ID");
      }
      const response = await put(`job-types/${jobTypeId}`, jobTypeData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "更新工作类型失败");
    }
  },

  async deleteJobType(id) {
    try {
      const jobTypeId = parseInt(id);
      if (isNaN(jobTypeId)) {
        throw new Error("无效的工作类型ID");
      }
      const response = await del(`job-types/${jobTypeId}`);
      return response;
    } catch (error) {
      throw new Error(error.message || "删除工作类型失败");
    }
  },

  async batchDeleteJobTypes(jobTypeIds) {
    try {
      const deletePromises = jobTypeIds.map((id) => this.deleteJobType(id));
      await Promise.all(deletePromises);
      return { success: true };
    } catch (error) {
      console.error("批量删除工作类型失败:", error);
      throw error;
    }
  },
};
